package com.taoding.hfhclient.netty_client.service;

import com.taoding.hfhclient.netty_client.*;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * @author liuxinghong
 * @Description: netty客户端收发消息api
 * @date 2019/9/4 000411:19
 */
@Slf4j
@Service
public class NettyClientMessageImpl implements NettyClientMessageService {


    /**
     * 向服务器发送消息
     * @param messageDTOList
     */
    @Override
    public  void sendMessage(List<MessageDTO> messageDTOList){
        Channel channel = NettyClient.future.channel();
        for (MessageDTO message:messageDTOList){
            ChannelFuture channelFuture =channel.writeAndFlush(message);
            channelFuture.addListener((ChannelFuture futureListener) -> {
                if (!futureListener.isSuccess()) { //断网后发送失败 监听 加入到失败容器中
                    ReSendTask.sendFailedMessage.add(message);
                    log.info("消息发送失败，已进入定时发送队列中...");
                }else {
                    log.info("发送成功----消息参数:"+NettyClient.future.channel().toString()+"\n 消息内容："+message.toString());
                }
            });
        }
        ClientHandler.idleCount=1; //发送消息后将心跳发送次数恢复为初始状态
    }

    /**
     * 接收服务器发来的消息
     */

    @Override
    public  void readMessage(MessageDTO message){
        //todo: 处理业务逻辑
        log.info("客户端收到的消息"+message.toString());
    }

    /**
     * 读取到当前消息后回复服务器端信息
     */
    @Override
    public  MessageDTO readMessageReply() {
        //todo： 执行业务逻辑
        return MessageDTO.builder().build();
    }

}
